
package com.yesep.learn.mqtt.server.broker.handler.protocol;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yesep.learn.mqtt.protocol.IUnSubscribe;
import com.yesep.learn.mqtt.server.common.Constants;
import com.yesep.learn.mqtt.server.common.subscribe.ISubscribeStoreService;
import com.yesep.learn.mqtt.util.ChannelUtil;

import io.netty.channel.Channel;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessageFactory;
import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.handler.codec.mqtt.MqttUnsubAckMessage;
import io.netty.handler.codec.mqtt.MqttUnsubscribeMessage;
import io.netty.util.AttributeKey;

/**
   * 消息编号：10
 * @Description: UNSUBSCRIBE连接处理，取消订阅
 */
@Service
public class UnSubscribe implements IUnSubscribe {

	private static final Logger LOGGER = LoggerFactory.getLogger(UnSubscribe.class);
	@Autowired
	private ISubscribeStoreService subscribeStoreService;

	public void process(Channel channel, MqttUnsubscribeMessage msg) {
		List<String> topicFilters = msg.payload().topics();
		String clientId = ChannelUtil.getClientId(channel);
		topicFilters.forEach(topicFilter -> {
			subscribeStoreService.remove(topicFilter, clientId);
			LOGGER.debug("UNSUBSCRIBE - clientId: {}, topicFilter: {}", clientId, topicFilter);
		});
		MqttUnsubAckMessage unsubAckMessage = (MqttUnsubAckMessage) MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.UNSUBACK, false, MqttQoS.AT_MOST_ONCE, false, 0), MqttMessageIdVariableHeader.from(msg.variableHeader().messageId()), null);
		channel.writeAndFlush(unsubAckMessage);
	}

}
